const Stores = require('./stores').Stores

export class Http {

    static headers() {

        const { token } = Stores.getUser()

        const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
        token && (headers['Authorization'] = `Bearer ${token}`)

        return headers
    }

    static reqeust_intercept(url, data) {
        return data
    }

    static response_intercept(url, res) {
        // wechat wapper content at second level
        return res.data || {}
    }

    static get(url, data) {

        if (typeof (data) == 'object') {
            data = this.reqeust_intercept(url, data)
            url = JSS.url_mix(url, data)
        }

        return new Promise((resolve, reject) => {
            wx.request({
                url,
                header: this.headers(),
                success: res => {
                    let data = this.response_intercept(url, res)
                    if (res.statusCode == 200) resolve(data)
                    else reject(res.errMsg)
                },
                fail: error => reject(error)
            })
        })
    }

    static post(url, data) {

        return new Promise((resolve, reject) => {
            wx.request({
                url,
                header: this.headers(),
                method: 'POST',
                data: this.reqeust_intercept(url, data),
                success: res => {
                    let data = this.response_intercept(url, res)
                    if (res.statusCode == 200) resolve(data)
                    else reject(res.errMsg)
                },
                fail: error => reject(error)
            })
        })
    }
}